import { Space, Typography, Row, Col, Button, message, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormSelect,
    ProFormSwitch,
    ProFormText,
    ProFormList,
    ProFormCascader,
} from '@ant-design/pro-form';
import $utils from '@/utils/utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';

import './index.less';
import { getUsersDetail, addUser, updateUser, getRegionData } from '@/services/user';
import { getJobsNames } from '@/services/jobs';

const { Title } = Typography;

// 区域选择当前选定，暂存储
let cur_regionItem: any = [], reg_dropdownVisible = false;
// 岗位选择当前选定，暂存储
let cur_JobItem: any = null, job_dropdownVisible = false;

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [userDetail, setUserDetail] = useState<any>();
    const [jobsNames, setJobsNames] = useState<any>();
    const [regionList, setRegionList] = useState<any>();
    // const [proListChange, updProListChange] = useState<any>();

    const [reg_visibleData, setReg_visibleData] = useState<any>({ 0: false });

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/System/users');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }
    else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';
    const isDetail: boolean = l_state?.status === 'detail';

    useEffect(() => {

        let new_data: API.Select[] = [], new_regionList: any = [];
        const getSelectData = async () => {
            try {

                const result = await getRegionData();
                new_regionList = [].concat(result);
                setRegionList(result);

                const msg = await getJobsNames({ name: '' });
                if (msg.code === 0) {
                    msg.body.map((item: { id: number, name: string, status: number }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                            disabled: item.status !== 1,
                        });
                    });
                    setJobsNames(new_data);
                }
            } catch (error) {
                message.error(`${error}`);
            }
        };
        getSelectData();

        const getUserData = async () => {
            try {
                const msg = await getUsersDetail({ id: cur_id });
                if (msg.code === 0) {
                    const data = Object.assign({}, msg.body);
                    const areaData: { area: any; }[] = [], jobsData: { jobName: number | undefined; }[] = [];

                    data.regionCodeList.map((item: any) => {
                        changeRegionList(new_regionList, item);

                        item[2] === '' && item.pop();
                        item[1] === '' && item.pop();
                        areaData.push({
                            area: item
                        });
                    });
                    data.positionList.map((item: any) => {
                        changeJobsList(new_data, item.id);
                        // const index = new_data.findIndex(i => i?.value === item.id);
                        // index > -1 && (new_data[index].disabled = true);
                        jobsData.push({
                            jobName: item.id,
                        });
                    });
                    data.status = msg.body.status === 1;
                    data.areaData = areaData;

                    data.jobsData = jobsData;
                    data.positionIds = data.jobsData.length > 0 ? data?.jobsData : [{ jobName: null }];
                    data.regionCodes = data?.areaData.length > 0 ? data?.areaData : [{ area: [] }];
                    new_regionList.length > 0 && setRegionList(new_regionList);
                    new_data.length > 0 && setJobsNames(new_data);
                    setUserDetail(data);

                    formRef && formRef.current?.resetFields();
                    return;
                }
            } catch (error) {
                message.error(`${error}`);
            }
        };

        if (!cur_id) {
            // 编辑切换回新建，需要清除数据
            getSelectData();
            setUserDetail(undefined);
            formRef && formRef.current?.resetFields();
        } else {
            !isCreate && getUserData();
        }
    }, [cur_id]);

    const changeJobsList = (new_data: any, id: any, status: boolean = true) => {
        const index = new_data.findIndex((i: any) => i?.value === id);
        index > -1 && (new_data[index].disabled = status);
        return new_data;
    };

    const changeRegionList = (new_regionList: any, item: any, status: boolean = true) => {
        new_regionList.map((i: any) => {
            if (i?.value !== item[0]) { return; }
            if (!item[2] && !item[1]) {
                i.disabled = status;
            }
            else if (!item[2] && item[1]) {
                i.children.map((i_son: any) => {
                    i_son?.value === item[1] && (i_son.disabled = status);
                });
            }
            else if (item[2]) {
                i.children.map((i_son: any) => {
                    if (i_son?.value !== item[1]) { return; }
                    i_son.children.map((s_son: any) => {
                        s_son?.value === item[2] && (s_son.disabled = status);
                    });
                });
            }
        });
    }

    return (
        <PageContainer>
            <ProCard style={{ marginTop: 8 }} gutter={8} >
                {(userDetail || isCreate) && <ProForm
                    layout={"horizontal"}
                    formRef={formRef}
                    onFinish={async (values) => {
                        const { positionIds, regionCodes, status, ...others } = values;
                        const newPositionIds: string[] = [], newRegionCodes: string[] = [];
                        positionIds.map((item: any) => {
                            newPositionIds.push(item.jobName);
                        });
                        regionCodes.map((item: any) => {
                            newRegionCodes.push(item.area.slice(-1));
                        });
                        let params = {
                            status: status ? 1 : 2,
                            positionIds: newPositionIds.join(','),
                            regionCodes: newRegionCodes.join(','),
                            ...others,
                        };
                        if (isCreate) {
                            const msg = await addUser(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '用户管理', path: '/System/users', isTopMenu: true });
                                    history.push('/System/users');
                                });
                            }
                        }
                        else if (isUpdate) {
                            params = Object.assign(params, { id });
                            const msg = await updateUser(params);
                            if (msg.code === 0) {
                                message.success('编辑成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '用户管理', path: '/System/users', isTopMenu: true });
                                    history.push('/System/users');
                                });
                            }
                        }
                    }}
                    initialValues={isCreate ? {
                        positionIds: [{ jobName: null }],
                        regionCodes: [{ area: [] }]
                    } : userDetail}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '8.333335%' }}>
                                    {!isDetail && <Button type="primary" htmlType="submit">保存</Button>}
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '用户管理', path: '/System/users', isTopMenu: true });
                                        history.push('/System/users');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <Title level={4} style={{ marginBottom: 26 }}>基本信息</Title>
                    <Row className={'form-row'}>
                        <Col span={8}>
                            <ProFormText
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                width={'md'}
                                name="phone"
                                label={'手机号'}
                                disabled={isDetail || isUpdate}
                                rules={[
                                    {
                                        required: true,
                                    },
                                    {
                                        len: 11,
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                width={'md'}
                                name="name"
                                label={'姓名'}
                                disabled={isDetail}
                                rules={[
                                    { required: true, },
                                    { min: 1, max: 15, },
                                    {
                                        pattern: new RegExp('[\u4E00-\u9FA5\uf900-\ufa2d]{1,}$', 'g'),
                                        message: '姓名只能输入汉字'
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row className={'form-row'}>
                        <Col span={8}>
                            <ProFormSelect
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                width={'md'}
                                name="isRoot"
                                label={'超级管理员'}
                                disabled={isDetail}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                                initialValue={0}
                                fieldProps={{
                                    options: [
                                        { label: '是', value: 1 },
                                        { label: '否', value: 0 },
                                    ]
                                }}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormSwitch
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 16 }}
                                name="status"
                                label="用户状态"
                                checkedChildren="启用"
                                unCheckedChildren="禁用"
                                initialValue={false}
                                disabled={isDetail}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row className={'form-row'}>
                        <Col span={24}>
                            <ProFormList
                                name={"positionIds"}
                                creatorButtonProps={false}
                                itemContainerRender={(doms, { field, fields, index, operation, record }) => {
                                    return (
                                        <ProForm.Group>
                                            <div onClick={() => {
                                                if (job_dropdownVisible && !!record && !cur_JobItem) {
                                                    let new_jobsNames = [].concat(jobsNames);
                                                    new_jobsNames = changeJobsList(new_jobsNames, record.jobName, false);
                                                    setJobsNames(new_jobsNames);
                                                    cur_JobItem = record.jobName;
                                                }
                                            }}>{doms}</div>
                                            {(!isDetail && fields.length !== 1) && <Button key='delete' onClick={() => {

                                                let new_jobsNames = [].concat(jobsNames);
                                                if (!!record) {
                                                    new_jobsNames = changeJobsList(new_jobsNames, record.jobName, false);
                                                    setJobsNames(new_jobsNames);
                                                }
                                                operation.remove(field.name);
                                            }}>删除</Button>}
                                            {(!isDetail && fields.length - 1) === index && <Button key='add' type="primary" onClick={() => {
                                                operation.add();
                                            }}>添加</Button>}
                                        </ProForm.Group>);
                                }}
                                copyIconProps={false}
                                deleteIconProps={false}
                                min={1}
                            >
                                <ProFormSelect
                                    labelCol={{ span: 8 }}
                                    wrapperCol={{ span: 16 }}
                                    options={jobsNames}
                                    disabled={isDetail}
                                    width="lg"
                                    name="jobName"
                                    label={'岗位名称'}
                                    fieldProps={{
                                        showSearch: true,
                                        allowClear: false,
                                        onChange: (value: any, selectedOptions: any) => {
                                            cur_JobItem = value;
                                        },
                                        onDropdownVisibleChange: (value: boolean) => {
                                            job_dropdownVisible = value;
                                            if (!value && !!cur_JobItem) {
                                                let new_jobsNames = [].concat(jobsNames);

                                                new_jobsNames = changeJobsList(new_jobsNames, cur_JobItem);
                                                setJobsNames(new_jobsNames);
                                            }
                                            else {
                                                cur_JobItem = null;
                                            }
                                        }
                                    }}
                                    rules={[
                                        {
                                            required: true,
                                        }
                                    ]}
                                />
                            </ProFormList>
                        </Col>
                    </Row>
                    <Title level={4} style={{ marginBottom: 26 }}>区域设置</Title>
                    <Row className={'form-row'}>
                        <Col span={24}>
                            <ProFormList
                                name={"regionCodes"}
                                creatorButtonProps={false}
                                itemContainerRender={(doms, { field, fields, index, operation, record }) => {
                                    return (
                                        <ProForm.Group>
                                            <div onClick={() => {
                                                if (reg_dropdownVisible && !!record && cur_regionItem.length === 0) {
                                                    const new_regionList = [].concat(regionList);
                                                    changeRegionList(new_regionList, record.area, false);
                                                    setRegionList(new_regionList);
                                                    cur_regionItem = record.area;
                                                }
                                            }}>
                                                <ProFormCascader
                                                    labelCol={{ span: 8 }}
                                                    wrapperCol={{ span: 16 }}
                                                    fieldProps={{
                                                        options: regionList,
                                                        changeOnSelect: true,
                                                        allowClear: false,
                                                        open: reg_visibleData[index],
                                                        onChange: (value: any, selectedOptions: any) => {
                                                            cur_regionItem = value;
                                                        },
                                                        onDropdownVisibleChange: (value: boolean) => {
                                                            reg_dropdownVisible = value;
                                                            setReg_visibleData({ [index]: value });
                                                            if (!value && cur_regionItem.length > 0) {
                                                                const new_regionList = [].concat(regionList);

                                                                changeRegionList(new_regionList, cur_regionItem);
                                                                setRegionList(new_regionList);
                                                            }
                                                            else {
                                                                cur_regionItem = [];
                                                            }
                                                        }
                                                    }}
                                                    width="lg"
                                                    name="area"
                                                    label={'所属区域'}
                                                    disabled={isDetail}
                                                    rules={[
                                                        {
                                                            required: true,
                                                        }
                                                    ]}
                                                />
                                            </div>
                                            {
                                                (!isDetail && fields.length !== 1) && <Button key='delete' onClick={() => {

                                                    const new_regionList = [].concat(regionList);
                                                    if (!!record && record?.area?.length > 0) {
                                                        changeRegionList(new_regionList, record.area, false);
                                                        setRegionList(new_regionList);
                                                    }
                                                    operation.remove(field.name);
                                                }}>删除</Button>
                                            }
                                            {
                                                (!isDetail && fields.length - 1) === index && <Button key='add' type="primary" onClick={() => {
                                                    operation.add();
                                                }}>添加</Button>
                                            }
                                        </ProForm.Group>);
                                }}
                                copyIconProps={false}
                                deleteIconProps={false}
                                min={1}
                            >

                            </ProFormList>
                        </Col>
                    </Row>
                </ProForm>}
            </ProCard >
        </PageContainer >
    );
};

export default Detail;
